package com.sto.stoapp.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sto.stoapp.adapter.BillControlsAdapter;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.BillControls;
import com.sto.stoapp.jpush.HttpGetControls;
import com.sto.stoapp.util.BillControlsUtil;
import com.sto.stoapp.util.NetUtil;
import com.sto.stoapp.widget.BaseActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wj on 2016-12-29.
 *
 * 面单管控展示界面
 */

public class StoBillControlsActivity extends BaseActivity {

    private static final int HTTP_FAILED=0;
    private static final int HTTP_EMPTY=1;
    private static final int HTTP_SUCESS=2;

    private ListView updateList;
    private Button backButton, updateButton, displayCount;
    private String titleName="面单发放记录";

    private List<BillControls.RulesBean> datas=new ArrayList<BillControls.RulesBean>();
    private BillControlsAdapter adapter;
    private TextView emptyTV;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case HTTP_FAILED:
                    Toast.makeText(StoBillControlsActivity.this,"请求数据失败",Toast.LENGTH_SHORT).show();
                    break;
                case HTTP_EMPTY:
                    adapter.notifyDataSetChanged();
                    displayCount.setText(datas.size()+"");
                    Toast.makeText(StoBillControlsActivity.this,"暂无面单信息",Toast.LENGTH_SHORT).show();
                    break;
                case HTTP_SUCESS:
                    if(datas.size()>0){
                        adapter.notifyDataSetChanged();
                        displayCount.setText(datas.size()+"");
                    }else {
                        updateList.setEmptyView(emptyTV);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sto_business_list);

        inintWidget();
        initListener();
        initdata();
    }

    private void initdata() {

        String oldRules= StoFilePreference.getInstance(this).getControlsRules();
        if(!"".equals(oldRules))
            datas.addAll(BillControlsUtil.str2List(oldRules));
        adapter=new BillControlsAdapter(datas,this);
        displayCount.setText(datas.size()+"");
        updateList.setAdapter(adapter);

    }

    private void inintWidget() {
        updateList = (ListView) findViewById(R.id.update_listview);
        updateButton = (Button) findViewById(R.id.list_update);
        backButton = (Button) findViewById(R.id.return_back);
        displayCount = (Button) findViewById(R.id.display_count);
        displayCount.setFocusable(false);
        emptyTV= (TextView) findViewById(R.id.tv_empty);

        setStoTitle(titleName);
    }

    private void initListener() {
        updateButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                updateListData();
            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 更新记录信息
     */
    private void updateListData(){

        //判断是否有网络连接
        if(!NetUtil.isNetworkAvailable(this)){
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                String lastTime=StoFilePreference.getInstance(StoBillControlsActivity.this).getControlsTime();
                if("".equals(lastTime)){
                    //第一次访问，取6个月之前的时间
                    lastTime= BillControlsUtil.get6MothAgoTime();
                }

                String netCode=StoFilePreference.getInstance(StoBillControlsActivity.this)
                        .getSiteCode();
                String result= HttpGetControls.getControls(netCode,lastTime);

                if(result==null || "".equals(result)){
                    mHandler.obtainMessage(HTTP_FAILED).sendToTarget();
                    return;
                }

                Log.e("wj","扫描管控获取到的数据："+result);
                BillControls bean=BillControlsUtil.str2Entity(result);

                if(null!=bean){

                    List<BillControls.RulesBean> list=new ArrayList<BillControls.RulesBean>();

                    //先获取本地管控规则
                    String oldRules=StoFilePreference.getInstance(StoBillControlsActivity.this).getControlsRules();
                    List<BillControls.RulesBean> oldList = BillControlsUtil.str2List(oldRules);
                    if(null!=oldList && oldList.size()>0){
                        //过滤旧数据
                        List<BillControls.RulesBean> fillterdList=BillControlsUtil.fillterList(oldList);
                        list.addAll(fillterdList);
                    }

                    //保存扫描管控开关
                    StoFilePreference.getInstance(StoBillControlsActivity.this).setControlsOnOff(bean.isInterceptOnOff());


                    if(bean.getRules().size()>0){
                        //保存获取时间
                        String endTime=bean.getRules().get(bean.getRules().size()-1).getEndTime();
                        StoFilePreference.getInstance(StoBillControlsActivity.this).setControlsTime(endTime);

                        list.addAll(bean.getRules());

                        //保存管控数据
                        String listStr=BillControlsUtil.list2Str(list);
                        StoFilePreference.getInstance(StoBillControlsActivity.this).setControlsRules(listStr);

                        datas.clear();
                        datas.addAll(list);
                        mHandler.sendEmptyMessage(HTTP_SUCESS);
                    }else {
                        //保存管控数据
                        datas.clear();
                        datas.addAll(list);
                        String listStr=BillControlsUtil.list2Str(list);
                        StoFilePreference.getInstance(StoBillControlsActivity.this).setControlsRules(listStr);
                        mHandler.sendEmptyMessage(HTTP_EMPTY);
                    }
                }else {
                    mHandler.obtainMessage(HTTP_FAILED).sendToTarget();
                }
            }
        }).start();
    }
}
